package com.tangsm.spring.boot.validation.config.filter;


import com.tangsm.spring.boot.validation.config.mvc.RequestWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Locale;

/**
 * 自定义Web过滤器
 *
 * @author tangsm
 * @since 2021/12/27
 */
//@Component
//@WebFilter(filterName = "requestFilter", urlPatterns = "/*")
public class RequestFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(RequestFilter.class);

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("过滤器初始化...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info("执行过滤开始...");

        // 此处针对application/json，防止流Body参数丢失，无法获取参数处理
        String contentType = request.getContentType().toLowerCase(Locale.ROOT);
        if (request instanceof HttpServletRequest && contentType.contains("application/json")) {
            chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
        }

        // 在chain.doFiler方法中传递新的request对象
        else {
            chain.doFilter(request, response);
        }
        log.info("执行过滤完成...");
    }

    @Override
    public void destroy() {
        log.info("过滤器销毁...");
    }
}
